import { Avatar, Button, Checkbox, Dropdown, Flex, Form, Input, message, Modal, Radio, Select, Space, type FormProps, type MenuProps } from "antd"
import type { CheckboxGroupProps } from "antd/es/checkbox"
import type React from "react"
import { useMemo, useState } from "react"
import { reqGetCaptcha } from "../../api/captchaApi"
import type { LoginForm, RegisterForm } from "../../types/userType"
import { reqCheckPwd, reqLogin, reqRegister, reqUpdatePwd } from "../../api/userApi"
import type { ROOTSTATE } from "../../store"
import { login, logout } from "../../store/userStore"
import { useDispatch, useSelector } from "react-redux"
import { Link, NavLink, useNavigate } from "react-router"
import "../../index.css"



const style: React.CSSProperties = {
   background: "#001E2E"
}
const loginOptions: CheckboxGroupProps<string>["options"] = [
   {
      label: "登录",
      value: "login"
   },
   {
      label: "注册",
      value: "register"
   }
]
export const Header = () => {
   const [open, setOpen] = useState(false)
   const [open1, setOpen1] = useState(false)
   const [type, setType] = useState<"login" | "register">("login")
   const [codeHTML, setCodeHTML] = useState("")
   const [form1] = Form.useForm()
   // const [user, setUser] = useState<User>()
   const { user, isLogin } = useSelector((state: ROOTSTATE) => state.userStore)
   const dispatch = useDispatch()
   const loginFinish: FormProps<LoginForm>["onFinish"] = async (values) => {
      const { token, code, msg, data } = await reqLogin(values)
      if (code == 0) {
         if (token) {
            if (values.noLogin) {
               localStorage.setItem("token", token)
            } else {
               sessionStorage.setItem("token", token)
            }
         }
         message.success("登录成功")
         dispatch(login(data))
         // setUser(data)
         setOpen(false)
      } else {
         message.error(msg)
      }


   }
   const registerFinish: FormProps<RegisterForm>["onFinish"] = async (values) => {
      const { msg, code } = await reqRegister(values)
      if (code == 0) {
         message.success(msg)
         setType("login")
      } else {
         message.error(msg)
         getCode()
      }
      console.log("values", values);
   }

   const form = useMemo(() => {
      if (type === 'login') {
         return <Form form={form1}
            labelCol={{ span: 4 }}
            onFinish={loginFinish}
            initialValues={{ noLogin: false }}
         >
            <Form.Item label="用户名"
               name="username"
               rules={[{ required: true, message: "请填写用户名" }]}>
               <Input></Input>
            </Form.Item>
            <Form.Item label="密码"
               name="password"
               rules={[{ required: true, message: "请填写密码" }]}>
               <Input type="password"></Input>
            </Form.Item>
            <Form.Item label="验证码"
               name="code"
               rules={[{ required: true, message: "请填写验证码" }]}>
               <Flex gap={20} align="flex-start">
                  <Input></Input>
                  <div
                     dangerouslySetInnerHTML={{ __html: codeHTML }}
                     style={{ width: 150, height: 50 }}></div>
               </Flex>
            </Form.Item>
            <Form.Item label={null}
               name="noLogin"
               valuePropName="checked">
               <Checkbox>30天免密登录</Checkbox>
            </Form.Item>
            <Form.Item label={null}>
               <Flex gap={30}>
                  <Button type="primary" htmlType="submit">
                     登录
                  </Button>
                  <Button onClick={() => form1.resetFields()}>重置</Button>
               </Flex>
            </Form.Item>
         </Form>
      }
      else {
         return <Form form={form1}
            labelCol={{ span: 4 }}
            onFinish={registerFinish}
         >
            <Form.Item label="用户名"
               name="username"
               rules={[{ required: true, message: "请填写用户名" }]}>
               <Input></Input>
            </Form.Item>
            <Form.Item label="昵称"
               name="nickname">
               <Input type="nickname"></Input>
            </Form.Item>
            <Form.Item label="验证码"
               name="code"
               rules={[{ required: true, message: "请填写验证码" }]}>
               <Flex gap={20} align="flex-start">
                  <Input></Input>
                  <div
                     dangerouslySetInnerHTML={{ __html: codeHTML }}
                     style={{ width: 150, height: 50 }}></div>
               </Flex>
            </Form.Item>
            <Form.Item label={null}>
               <Flex gap={30}>
                  <Button type="primary" htmlType="submit">
                     注册
                  </Button>
                  <Button onClick={() => form1.resetFields()}>重置</Button>
               </Flex>
            </Form.Item>
         </Form>
      }
   }, [type, codeHTML])

   //获取验证码的方法
   const getCode = async () => {
      const { data } = await reqGetCaptcha()
      setCodeHTML(data)
   }

   //退出登录
   const logoutFn = () => {
      dispatch(logout());
      localStorage.removeItem("token");
      sessionStorage.removeItem("token");
   }
   //下拉选项
   const items: MenuProps["items"] = [
      {
         key: "1",
         label: <Link to="/home">个人页面</Link>,
      },
      {
         key: "2",
         label: (
            <div onClick={() => { setOpen1(true) }}>修改密码</div>
         ),
      },
      {
         key: "3",
         label: "我的评论",
         disabled: true,
      },
      {
         key: "4",
         label: "我的问题",
         disabled: true,
      },
      {
         key: "5",
         label: <div onClick={logoutFn}>退出登录</div>
      }
   ]

   // console.log(reqGetCaptcha)
   //  const val =await reqGetCaptcha()
   // setCodeHTML(val.data)
   //修改密码的form
   const [pwdForm] = Form.useForm();
   const [value,setValue] = useState("");
   const [searchType,setSearchType] =useState("issue")
   const navigate =useNavigate()
   const searchFn =()=>{
      if(value === ""){
         navigate("/issue")
      }else{
         navigate(`/search?type=${searchType}&value=${value}`)
      }
   }
   return (
      <>
         <Flex style={style}>
            <Flex style={{ width: 1200, margin: "0 auto" }}
               align="center"
               justify="space-between">
               <img src="/logo2.png" style={{ height: 60 }} />
               <Flex>
                  <NavLink to="/issue">
                     <Button type="link">问答</Button>
                  </NavLink>
                  <NavLink to="/book">
                     <Button type="link">书籍</Button>
                  </NavLink>
                  <NavLink to="/qa">
                     <Button type="link">面试题</Button>
                  </NavLink>
                  <a href="http://www.niaodi.cn/" target="_plank">
                     <Button type="link">在线课程</Button>
                  </a>

               </Flex>
               <Space.Compact>
                  <Select
                     style={{ width: 100 }}
                     defaultValue={searchType}
                     options={[
                        { value: 'issue', label: '问答' },
                        { value: 'book', label: '书籍' }
                     ]}
                     onChange={(e)=>setSearchType(e)}
                  />
                  <Input onChange={(e)=>setValue(e.target.value)}></Input>
                  <Button type="primary" onClick={searchFn}>搜索</Button>
               </Space.Compact>
               {!isLogin ? (<Button type="primary" onClick={() => {
                  setOpen(true)
                  getCode()
               }}>登录/注册</Button>)
                  : (
                     <div>
                        <Dropdown menu={{ items }}>
                           <Avatar size={64} src={user.avatar} />
                        </Dropdown>
                     </div>

                  )}
            </Flex>
         </Flex>
         {/* 登录|注册弹窗 */}
         <Modal title="登录/注册" open={open} footer={null}
            onCancel={() => setOpen(false)}>
            <Radio.Group
               block
               value={type}
               onChange={(e) => {
                  setType(e.target.value)
                  getCode()
               }}
               options={loginOptions}
               optionType="button"
               buttonStyle="solid"
               style={{
                  marginBottom: 30
               }}
            />
            {form}
         </Modal>
         <Modal
            open={open1}
            onCancel={() => setOpen1(false)}
            footer={null}
            title="修改密码"
         >
            <Form labelCol={{ span: 4 }} form={pwdForm} onFinish={async (values) => {
               await reqUpdatePwd(user.username, values.newpwd)
               setOpen1(false);
               pwdForm.resetFields()
               //退出登录
               //表单置空
               logoutFn()
            }}>
               <Form.Item
                  validateDebounce={1000}
                  hasFeedback
                  label="原始密码"
                  name="oldpwd"
                  rules={[
                     {
                        validator: async (_, value: string) => {
                           const { code } = await reqCheckPwd(user.username, value)
                           if (code != 0) {
                              throw Error("原始密码不正确")
                           }
                        }
                     }
                  ]}>
                  <Input.Password></Input.Password>
               </Form.Item>
               <Form.Item label="新密码" name="newpwd"
                  validateDebounce={1000}
                  hasFeedback
                  rules={
                     [
                        {
                           required: true,
                           message: "填写新的密码"
                        },
                        {
                           pattern: /^[0-9a-zA-Z@$]+$/g,
                           message: "密码只能由数字字母@!组成"
                        },
                        {
                           max: 10,
                           min: 6,
                           message: "密码长度在6-10位"
                        }
                     ]
                  }>
                  <Input.Password></Input.Password>
               </Form.Item>
               <Form.Item label="确认密码" name="checkpwd" validateDebounce={1000} hasFeedback
                  rules={[
                     {
                        validator: async (_, value) => {
                           if (value === " ") {
                              throw Error("再次输入密码")
                           }
                           const newValue = pwdForm.getFieldValue("newpwd");
                           const oldValue = pwdForm.getFieldValue("oldpwd");
                           if (value === oldValue) {
                              throw Error("新密码不能与老密码相同")
                           }
                           if (value != newValue) {
                              throw Error("两次密码不一致")
                           }
                        }
                     }
                  ]}>
                  <Input.Password></Input.Password>
               </Form.Item>
               <Form.Item label={null}>
                  <Flex gap={20}>
                     <Button type="primary" htmlType="submit">确认</Button>
                     <Button htmlType="reset">重置</Button>
                  </Flex>
               </Form.Item>
            </Form>
         </Modal>
      </>
   )
}


